/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tk.zater.File;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
import tk.zater.obj.CS;

/**
 *
 * @author zater
 */
public class ReadFile {

    public Object readfile(String ClassName, String fileName) throws Exception {
        Class<?> objectClass = Class.forName(ClassName);
        Field[] objectFields = objectClass.getDeclaredFields();
        Properties prop = new Properties();
        prop.load(new FileInputStream(new File(fileName)));
        Object q = objectClass.newInstance();
        for (int i = 0; i < objectFields.length; i++) {
            String CSName = objectFields[i].getName();
            Method tempfun = objectClass.getMethod(createGetterFunction(CSName));
            Object temp = tempfun.invoke(q);
            if (temp instanceof CS) {
                //  不是-->不读取  
                CS<?> CS = (CS)tempfun.invoke(q);
                Class<?> Eclass = CS.myEclass();
                Constructor CScon= Eclass.getConstructor(String.class);
                CS.setValue(CScon.newInstance(prop.getProperty(CSName)));
                tempfun= objectClass.getMethod(createSetterFunction(CSName),CS.class);
                tempfun.invoke(q,CS);
                
            }else{
                continue;
            }
        }
        System.out.println(q);
        return q;
    }

    private String createGetterFunction(String Name) {
        StringBuffer buf = new StringBuffer("get");
        if (String.valueOf(Name.charAt(0)).matches("[a-z]")) {
            buf.append((char) ((int) Name.charAt(0) - 32));
        }
        buf.append(Name.substring(1));
        return buf.toString();
    }
    private String createSetterFunction(String Name) {
        StringBuffer buf = new StringBuffer("set");
        if (String.valueOf(Name.charAt(0)).matches("[a-z]")) {
            buf.append((char) ((int) Name.charAt(0) - 32));
        }
        buf.append(Name.substring(1));
        return buf.toString();
    }
}
